import React, { useEffect, useState, useRef } from 'react';
import {
  View,
  Image,
  Text,
  Button
} from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro';
import {
  postMaxImgDownLoad,
  queryUserImgDEL,
  queryTaskById,
} from '@/api';
import NavBar from '@/components/NavBar';
import './detail.scss';

const MyportrayDetail = () => {
  const router = useRouter();
  const [titleBarHeight, setTitleBarHeight] = useState(0);
  const [img, setImg] = useState('');
  const [use_num, setUseNum] = useState('');
  const [tmpl_name, setTmplName] = useState('');
  const [id, setId] = useState(null);
  const siv = useRef(null);

  useShareAppMessage((res)=>{
    if (res.from == 'button') {
      onPostInvitations();
      return {
        title: '快来围观我的写真吧',
        path: '/pages/index/index',
        imageUrl: 'https://jala-test-images.sndaurl.cn/images/share_img.png'
      }
    }
  })

  useEffect(() => {
    Taro.getSystemInfo({
      success: (res) => {
        let height = res.titleBarHeight + res.statusBarHeight
        setTitleBarHeight(height)
      }
    });
    let params = router.params;
    let {
      img,
      tmpl_name,
      use_num,
      id
    } = params;
    setId(id)
    setImg(img);
    setUseNum(use_num);
    setTmplName(tmpl_name);
    return () => {
      clearInterval(siv.current)
    };
  }, []);

  const onHdImgDownLoad = () => {
    postMaxImgDownLoad({img_url: img})
      .then(res=>{
        Taro.showLoading({
          title: '加载中',
        });
        siv.current = setInterval(()=>{
          queryTaskById({task_id: res.TaskId})
            .then(data=>{
              if (data.Status == "Success") {
                clearInterval(siv.current);
                Taro.downloadFile({
                  url: data.Result.data.url,
                  header: {
                    "content-type": "application/json",
                  },
                  success: (response) => {
                    Taro.saveImageToPhotosAlbum({
                      filePath: response.tempFilePath, // 暂不支持网络图片/本地图片地址，需与tt.downloadFile一起使用
                      success: (res) => {
                        Taro.showToast({ title: "成功保存到本地相册" });
                      },
                      fail: (err) => {
                        let errType = err.errMsg.includes(
                          "saveImageToPhotosAlbum:fail cancel"
                        )
                          ? "取消保存"
                          : "保存失败";
                          Taro.showModal({
                          title: errType,
                          content: err.errMsg,
                          showCancel: false,
                        });
                      },
                    });
                  },
                  fail: (res) => {
                    console.log("downloadFile fail", res);
                    tt.showToast({
                      title: res.errMsg,
                      icon: "none",
                    });
                  },
                  complete: (res) => {
                    console.log("downloadFile complete", res);
                  },
                });
              }
            });
        }, 2000)
      })
  }

  const hdDownload = () => {
    Taro.getSetting().then(res => {
      if (!res.authSetting['scope.album']) {
        Taro.authorize({
          scope: 'scope.album',
          success () {
            onHdImgDownLoad();
          }
        }).catch(() => {
          Taro.showModal({
            content: '检测到您没打开下载图片功能权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: "取消",
            confirmColor: '#FF3377',
            cancelColor: '#666666',
            success (res2) {
              //点击“确认”时打开设置页面
              if (res2.confirm) {
                Taro.openSetting({
                  success (res3) {
                    if (res3.authSetting['scope.album']) {
                      onHdImgDownLoad();
                    }
                  }
                })
              } else {
              }
            }
          })
        })
      } else {
        onHdImgDownLoad();
      }
    });
  }

  const onDownload = () => {
    Taro.getSetting().then(res => {
      if (!res.authSetting['scope.album']) {
        Taro.authorize({
          scope: 'scope.album',
          success () {
            onNormalDownLoad();
          }
        }).catch(() => {
          Taro.showModal({
            content: '检测到您没打开下载图片功能权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: "取消",
            confirmColor: '#FF3377',
            cancelColor: '#666666',
            success (res2) {
              //点击“确认”时打开设置页面
              if (res2.confirm) {
                Taro.openSetting({
                  success (res3) {
                    if (res3.authSetting['scope.album']) {
                      onNormalDownLoad();
                    }
                  }
                })
              } else {
              }
            }
          })
        })
      } else {
        onNormalDownLoad();
      }
    });
  }

  const onNormalDownLoad = () => {
    Taro.downloadFile({
      url: img,
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        let filePath = res.tempFilePath;
        Taro.saveImageToPhotosAlbum({
          filePath, // 暂不支持网络图片/本地图片地址，需与tt.downloadFile一起使用
          success: (res) => {
            Taro.showToast({ title: "成功保存到本地相册" });
          },
          fail: (err) => {
            let errType = err.errMsg.includes(
              "saveImageToPhotosAlbum:fail cancel"
            )
              ? "取消保存"
              : "保存失败";
              Taro.showModal({
              title: errType,
              content: err.errMsg,
              showCancel: false,
            });
          },
        });
      },
      fail: (err) => {
        Taro.showModal({
          title: "下载出错",
          content: err.errMsg,
          showCancel: false,
        });
      },
    });
  }

  const onRemove = () => {
    Taro.showActionSheet({
      itemList: ['删除'],
      itemColor: '#1B1B1B',
      success: function (res) {
        console.log(res.tapIndex)
        let {
          tapIndex
        } = res;
        if (tapIndex === 0) {
          queryUserImgDEL({id: id})
            .then(response=>{
              Taro.showToast({
                title: '删除成功',
                icon: 'none',
                success: () => {
                  Taro.showToast({
                    title: '删除成功',
                    icon: 'none',
                    duration: 2000
                  })
                  setTimeout(()=>{
                    Taro.navigateBack();
                  }, 2000);
                }
              });
            })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  }

  const onChooseTemplate = () => {
    let params = router.params;
    let {
      tmpl_name,
      tmpl_id,
      tmpl_img,
      tmpl_tmb_img,
      use_num,
      number,
      backdrop_img
    } = params;
    // Taro.navigateTo({
    //   url: `/pages/index/index?tmpl_name=${tmpl_name}&tmpl_tmb_img=${tmpl_tmb_img}&tmpl_img=${tmpl_img}&tmpl_id=${tmpl_id}&use_num=${use_num}&number=${number}&backdrop_img=${backdrop_img}`
    // })
    Taro.reLaunch({
      url: `/pages/index/index?tmpl_name=${tmpl_name}&tmpl_tmb_img=${tmpl_tmb_img}&tmpl_img=${tmpl_img}&tmpl_id=${tmpl_id}&use_num=${use_num}&number=${number}&backdrop_img=${backdrop_img}`
    })
  }

  return (
    <View className='myportray_main'>
      {/* <NavBar
        title="我的写真"
        onClick={()=>{doBack()}}
      /> */}
      <View
        className='myportray_section'
        style={{
          paddingTop: `${titleBarHeight}px`
        }}
      >
        <View
          style={{
            height: `calc(100vh - ${titleBarHeight}px)`
          }}
          className='myportray_content'
        >
          <View className='myportray_content_scetion'>
            <View className='myportray_content_main'>
              <View className='myportray_content_block'>
                <Image
                  src={img}
                  className='myportray_content_block_img'
                  mode='aspectFill'
                />
                <View className='myportray_content_block_info'>
                  <View className='myportray_content_block_info_label'>
                    <Image
                      src='https://jala-test-images.sndaurl.cn/images/makeup.png'
                      className='myportray_content_block_info_label_icon'
                    />
                    {tmpl_name}
                  </View>
                  已有{use_num}人使用
                </View>
              </View>
              <View className='myportray_content_block remote'>
                <Image
                  src={img}
                  className='myportray_content_block_img'
                />
                <View className='myportray_content_block_info'>
                  <View className='myportray_content_block_info_label'>
                    <Image
                      src='https://jala-test-images.sndaurl.cn/images/makeup.png'
                      className='myportray_content_block_info_label_icon'
                    />
                    {tmpl_name}
                  </View>
                  已有{use_num}人使用
                </View>
              </View>
            </View>
            <View
              className='myportray_content_actions'
              onClick={()=>{
                onChooseTemplate()
              }}
            >
              <View className='myportray_content_action'>使用模版再次变妆</View>
            </View>
          </View>
          <View className='myportray_footer'>
            <View className='myportray_footer_tip'>
              <View className='myportray_footer_tip_value'>
              点击分享您的美
              </View>
            </View>
            <View className='myportray_footer_action'>
              <View className='myportray_footer_action_item' onClick={()=>{hdDownload()}}>
                <Image
                  src='https://jala-test-images.sndaurl.cn/images/actions/HdDownloda.png'
                  className='myportray_footer_action_item_icon'
                  mode='aspectFill'
                />
                <View className='myportray_footer_action_item_text'>高清下载</View>
              </View>
              <View className='myportray_footer_action_item' onClick={()=>{onDownload()}}>
                <Image
                  src='https://jala-test-images.sndaurl.cn/images/actions/download.png'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>下载</View>
              </View>
              <Button
                openType='share'
                className={`myportray_footer_action_item`}
              >
                <Image
                  src='https://jala-test-images.sndaurl.cn/images/actions/share_icon.png'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>分享</View>
              </Button>
              {/* <Button
                openType='share'
                className='myportray_footer_action_item'
              >
                <Image
                  src='https://jala-test-images.sndaurl.cn/images/actions/share.png'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>分享小程序</View>
              </Button> */}
              <View className='myportray_footer_action_item' onClick={()=>{onRemove()}}>
                <Image
                  src='https://jala-test-images.sndaurl.cn/images/actions/delete.png'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>删除</View>
              </View>
            </View>
          </View>
        </View>
      </View>
    </View>
  )
}
export default MyportrayDetail;
